package com.lorizz.picpub.web;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.lorizz.upm.UserProfile;
import com.lorizz.upm.np.NPUtils;
import com.lorizz.upm.np.UserProfileNP;

public class TokenInterceptor implements HandlerInterceptor {
	
	private TokenGenerator tokenGenerator;
	private String cookieName = "ut";

	public void setTokenGenerator(TokenGenerator tokenGenerator) {
		this.tokenGenerator = tokenGenerator;
	}

	public void setCookieName(String cookieName) {
		this.cookieName = cookieName;
	}

	@Override
	@Transactional
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		UserProfileNP userProfileNP = (UserProfileNP) request.getSession().getAttribute(Constants.SESSION_USERPROFILE);
		if (userProfileNP != null)
			return true;
		if (request.getCookies() == null)
			return true;
		for (Cookie cookie : request.getCookies()) {
			if(cookieName.equalsIgnoreCase(cookie.getName())) {
				String token = cookie.getValue();
				if (token != null && token.length() > 0) {
					UserProfile userProfile = tokenGenerator.evaluate(token);
					if (userProfile != null) {
						request.getSession().setAttribute(Constants.SESSION_USERPROFILE, NPUtils.packageUserProfile(userProfile));
					}
				}
			}
		}
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		
	}

}
